package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.ShiftMapper;
import com.example.mapper.SignInMapper;
import com.example.mapper.WorkScheduleMapper;
import com.example.pojo.Shift;
import com.example.pojo.SignIn;
import com.example.pojo.WorkSchedule;
import com.example.service.IWorkScheduleService;
import com.example.util.DateUtils;
import com.example.vo.ResultVo;
import com.example.vo.per.ClockInParams;
import com.example.vo.per.WorkScheduleParams;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 排班表 服务实现类
 * </p>
 *
 * @author wsl
 * @since 2022-04-28
 */
@Service
public class WorkScheduleServiceImpl extends ServiceImpl<WorkScheduleMapper, WorkSchedule> implements IWorkScheduleService {
    
    @Autowired
    private WorkScheduleMapper wsm;
    @Autowired
    private SignInMapper sim;
    @Autowired
    private ShiftMapper sm;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo insByListWorkSchedule(WorkScheduleParams wsp) {

        for (Integer id : wsp.getWorkIds()) {
            WorkSchedule ws = new WorkSchedule();
            ws.setShiftId(wsp.getShiftId());
            ws.setWorkId(id);
            ws.setClosureDate(wsp.getClosureDate());
            ws.setInitiateDate(wsp.getInitiateDate());

            wsm.insert(ws);
        }
        return ResultVo.ok();
    }

    @Override
    public List<Map<String,Object>> selByListWorkSchedule(Integer datasel, Integer statussel, Integer pageNum,Integer pageSize) {
        return wsm.selectByShiftIdAndStatus(datasel, statussel);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delByworids(Integer[] ids) {
        for (Integer id : ids) {
            WorkSchedule schedule = wsm.selectOne(new QueryWrapper<WorkSchedule>()
                    .setEntity(new WorkSchedule()
                            .setWorkId(id)));

            System.err.println("schedule -> "+ schedule);

            wsm.update(schedule,new UpdateWrapper<WorkSchedule>()
                    .eq("work_id",id)
                    .set("status",1));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ClockInParams> sellistcip(Integer workid,Integer monthStatus) {
        List<ClockInParams> list = wsm.sellistcip(workid,monthStatus);
        list.forEach(o->{
            Shift shift = sm.selectById(o.getShiftId());
            uptSign(o.getRangeDays().get(0),o.getRangeDays().get(1),o.getWorkId(),shift.getDuration());
        });
        return list;
    }

    @Override
    public void uptSign(String staTIme, String endTime, Integer worid, Integer onup) {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        try {
            Date d1 = sdf.parse(staTIme);
            Date d2 = sdf.parse(endTime);
            List<String> days = DateUtils.getTimeRangeDay(d1, d2);
            List<SignIn> ins = sim.selListBywWorId(worid);
            List<String> list = new ArrayList<>();
            // 迟到处理
            uptSignInsOne(worid,onup);
            // 当日之前打卡日期
            List<String> daylist = new ArrayList<>();
            Date now = new Date();
            days.forEach(o->{
                try {
                    if (sdf.parse(o).getTime() < now.getTime()){
                        daylist.add(o);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            });
            // 取出已打卡日期
            ins.forEach(o->{list.add(String.valueOf(o.getSignDate())); });
            // 删除相同值
            daylist.removeIf(s-> list.contains(s));
            // 排班日期未打卡
            daylist.forEach(o->{
                System.err.println(" -- < " + o);
                SignIn in = new SignIn();
                in.setWorkId(worid);
                in.setSignDate(LocalDate.parse(o, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                in.setSignTime(LocalTime.now());
                in.setStatus(2);
                sim.insert(in);
            });
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void uptSignInsOne(Integer worid, Integer onup) {
        List<SignIn> signIns = sim.selSignCount(worid);
        if (signIns.size() < onup && signIns.size() != 0){
            SignIn signIn = new SignIn();
            signIn.setWorkId(worid);
            signIn.setStatus(1);
            signIn.setSignDate(LocalDate.now().minusDays(1));
            signIn.setSignTime(LocalTime.now());
            sim.insert(signIn);
        }
    }


}
